package com.suian.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.stream.Collectors;

public class FileUtil {
    public static void main(String[] args) throws IOException {
        String path = "D:\\suian\\javacode\\springcloud\\spring-cloud-demo\\product-service\\src\\main\\resources\\source.txt";
        String target = "D:\\suian\\javacode\\springcloud\\spring-cloud-demo\\product-service\\src\\main\\resources\\target.txt";

        ArrayList<ArrayList<Integer>> rows = new ArrayList<>();
        //从source.txt文件中读取出二维数组，每行包含若干个整数，请按一下要求处理数据
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line;
        int lineNo = 0;
        while ((line = br.readLine()) != null) {
            lineNo++;
            System.out.println(line);
            String[] s = line.split(" ");

            //在每一行内去除重复的数字,利用hashSet
            HashSet<Integer> lineSet = new HashSet<>();
            for (String str : s) {
                lineSet.add(Integer.parseInt(str));
            }
            ArrayList<Integer> lineList = new ArrayList<>(lineSet);
            //排序
            if (lineNo % 2 == 1) {
                //奇数行，升序
                Collections.sort(lineList);
            } else {
                //偶数行，降序
                Collections.sort(lineList,Collections.reverseOrder());
            }

            //累加和加到最后一个
            int sum = 0;
            for (Integer i : lineList) {
                sum += i;
            }
            lineList.add(sum);
            System.out.println("第"+lineNo+"行 set:"+lineSet);
            rows.add(lineList);
        }

        System.out.println("=======解析后的数据=======");
        System.out.println(rows);

        //3、将处理好的数据写入target.txt文件
        writeFileFun(rows, target);
    }

    //写入文件
    private static void writeFileFun(ArrayList<ArrayList<Integer>> rows, String target) throws IOException {
        BufferedWriter bw = null;
        try {
             bw = new BufferedWriter(new FileWriter(target));
            for (ArrayList<Integer> row : rows) {
                String line = "";
                for (Integer i : row) {
                    line += i+" ";
                }
                bw.write(line);
                bw.newLine();
            }
        } finally {
            bw.close();
        }
    }
}
